<template>
  <div>
    <yt-crud
      v-bind="options"
      ref="crudRef"
      @onLoad="getData"
      :fun-props="{
        exportBtn: false,
        delBtn: false,
        addBtn: true,
      }"
      :table-props="{
        selection: false,
        delBtn: true,
        viewBtn: true,
        editBtn: true,
        menuSlot: true,
        menuWidth: 200,
      }"
      :form-props="{
          loading: state.form.loading,
          width: 500,
        }"
      :loading="state.loading"
      :total="state.total"
      v-model:page="state.page"
      v-model:query="state.query"
      @delFun="handleDelete"
      @saveFun="onSave"
      @openBeforeFun="openBeforeFun"
      @change="onChange"
    >
      <template #rightToolbar></template>
      <template #menuSlot></template>
      <template #scope="scope:any">
        <el-tooltip class="box-item" :content="scope.row.scope === 'All' ? PromotionScopeEnum.All.label : scope.row.stationNames" placement="top-start">
          <DictTag :options="PromotionScopeEnum" :value="scope.row.scope" />
        </el-tooltip>
      </template>
      <template #type="scope:any">
        <el-tooltip class="box-item" :content="scope.row.properties" placement="top-start">
          <DictTag :options="PromotionTypeEnum" :value="scope.row.type" />
        </el-tooltip>
      </template>
      <template #status="scope:any">
        <el-switch v-model="scope.row.status" active-value="Enabled" inactive-value="Disabled" @change="handleStatusChange(scope.row)" />
      </template>

      <template #rangeTime="scope:any"> {{parseTime(scope.row.startTime, '{y}-{m}-{d}')}} - {{parseTime(scope.row.endTime, '{y}-{m}-{d}')}} </template>
      <template #propertiesFormItem="scope:any">
        <el-form-item v-if="scope.row.type === 'ServiceDiscount' || scope.row.type === 'ServiceAndParkDiscount'" :label="t('business.promotion.discount.discount')" prop="properties.discount" :rules="[{ required: true, message: t('business.promotion.discount.validator.discount') }]">
          <el-input-number :min="0.01" :max="1.00" :precision="2" :step="0.1" v-model="scope.row.properties.discount" :placeholder="t('business.promotion.placeholder.discount')"></el-input-number>
        </el-form-item>
      </template>
    </yt-crud>
  </div>
</template>

<script lang="ts" setup>
import { IColumn } from '@/components/common/types/tableCommon'
import { list as promotionList, remove as promotionRemove, save as promotionSave, batchRemove as promotionBatchRemove, changeStatus } from '@/api/business/promotion'
import {getStationList} from '@/api/business/station'
import YtCrud from '@/components/common/yt-crud.vue'
import {ComponentInternalInstance} from 'vue'
import {useI18n} from 'vue-i18n'
import {parseTime} from '@/utils/ruoyi'

const { t } = useI18n()

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { EnableStatusEnum, PromotionScopeEnum, PromotionTypeEnum } = toRefs<any>(proxy?.useEnum('enable_status_enum', 'promotion_scope_enum', 'promotion_type_enum'))

const state = reactive({
  form: {
    loading: false,
  },
  page: {
    pageSize: 30,
    pageNum: 1,
  },
  total: 0,
  loading: false,
  query: {},
})

const stations = ref<any[]>([])
const loadStations = () => {
  getStationList({
    pageSize: 9999,
    pageNum: 1,
  })
    .then((res) => {
      stations.value = res.data.rows
    })
    .finally(() => {
      state.loading = false
    })
}
loadStations()

const column = ref<IColumn[]>([
  {
    label: t('business.promotion.name'),
    searchLabelWidth: 120,
    key: 'name',
    search: true,
    formHide: false,
    colSpan: 22,
    componentProps: {
      style: 'width:100%',
    },
    rules: [{ required: true, message: t('business.promotion.validator.name') }],
  },
  {
    label: t('business.promotion.scope'),
    key: 'scope',
    colSpan: 22,
    type: 'select',
    componentProps: {
      options: PromotionScopeEnum,
      style: 'width:100%',
    },
    rules: [{ required: true, message: t('business.promotion.validator.scope') }],
    search: true,
    formHide: false,
    slot: true,
    formWatch: (scope) => {
      scope.column.forEach((f: IColumn) => {
        if (f.key === 'stationIds') {
          f.formHide = scope.value === 'All' || scope.value == undefined
          if(scope.value === 'All') {
            scope.data.stationIds = []
          }
        }
      })
      column.value = scope.column
    },
  },
  {
    label: t('business.promotion.stationIds'),
    key: 'stationIds',
    colSpan: 22,
    type: 'i18nMultipleSelect',
    componentProps: {
      keyAlias: 'id',
      valueAlias: 'name',
      options: stations,
      placeholder: t('business.promotion.placeholder.stationIds')
    },
    rules: [{ required: true, message: t('business.promotion.validator.stationIds') }],
    hide: true,
    search: false,
    formHide: true,
    slot: true,
  },
  {
    label: t('business.promotion.type'),
    key: 'type',
    colSpan: 22,
    type: 'select',
    componentProps: {
      options: PromotionTypeEnum,
      style: 'width:100%',
    },
    rules: [{ required: true, message: t('business.promotion.validator.type') }],
    search: true,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.promotion.properties'),
    key: 'properties',
    hide: true,
    slot: true,
    formItemSlot: true,
  },
  {
    label: t('business.promotion.rangeTime'),
    key: 'rangeTime',
    colSpan: 22,
    type: 'date',
    componentProps: {
      type: 'daterange',
      rangeSeparator: '-',
      startPlaceholder: t('crud.table.column.startTime'),
      endPlaceholder: t('crud.table.column.endTime'),
    },
    rules: [{ required: true, message: t('business.promotion.validator.rangeTime') }],
    search: false,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.promotion.status'),
    key: 'status',
    type: 'select',
    componentProps: {
      options: EnableStatusEnum,
    },
    search: true,
    formHide: true,
    slot: true,
    rules: [{ required: true, message: t('business.promotion.validator.status') }],
  },
  {
    label: t('crud.table.column.note'),
    key: 'note',
    hide: true,
    formHide: false,
    colSpan: 22,
    componentProps: {
      type: 'textarea',
      rows: 5,
    }
  },
  {
    label: t('crud.table.column.createTime'),
    key: 'createTime',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    formHide: true,
  },
])
const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  promotionList({
    ...state.page,
    ...state.query,
  })
    .then((res) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}

// 保存数据
const onSave = async ({ data, cancel }: any) => {
  state.form.loading = true
  data.startTime = data.rangeTime[0]
  data.endTime = data.rangeTime[1]
  data.properties = JSON.stringify(data.properties)
  promotionSave(toRaw(data)).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    cancel()
    getData()
  }).finally(()=>{
    state.form.loading = false
  })

}
// 弹窗前置操作
const openBeforeFun = ({ type, data }) => {
  if (type === 'add') {
    data.properties = {}
  } else if (type === 'update') {
    data.properties = JSON.parse(data.properties)
    data.rangeTime= [data.startTime, data.endTime]
  }
}

// 删除
const handleDelete = async (row: any) => {
  state.loading = true
  if (row instanceof Array) {
    promotionBatchRemove(row.map((m) => m.id)).then(()=>{
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    }).finally(()=>{
      state.loading = false
    })
  } else {
    promotionRemove(row.id).then(()=>{
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    }).finally(()=>{
      state.loading = false
    })
  }
}

/** 状态修改  */
const handleStatusChange = async (row: any) => {
  if(!row.id)  return
  try {
    await proxy?.$modal.confirm(row.status === 'Enabled' ? t('crud.action.tooltip.enable') : t('crud.action.tooltip.disabled'))
    await changeStatus(row.id, row.status)
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  } catch (err) {
    row.status = row.status === 'Enabled' ? 'Disabled' : 'Enabled'
  }
}

const multipleSelection = ref<{ deviceId: string }[]>([])

const onChange = (data) => {
  multipleSelection.value = data
}

const options = reactive({
  ref: 'crudRef',
  data,
  column,
})
</script>


